package com.zunipe.ftpe;

import com.zunipe.ftpe.util.ZI18n;
import com.zunipe.ftpe.util.ZLog;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;

public class FTPClientWrapper {
    public static final String TAG = "FTPClientWrapper";

    private final String hostname;
    private final int port;
    private final String username;
    private final String password;

    private FTPClient ftpClient;

    public FTPClientWrapper(String hostname, int port, String username, String password) {
        ftpClient = new FTPClient();
        this.hostname = hostname;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    public FTPClient getFtpClient() throws IOException {
        if (ftpClient == null) {
            ftpClient = new FTPClient();
        }
        if (!ftpClient.isConnected()) {
            login();
        }
        try {
            ftpClient.listDirectories();
        } catch (IOException e) {
            ZLog.i(TAG, ZI18n.getString("client_wrapper.info.connection_timeout"));
            ftpClient.disconnect();
            login();
        }
        return ftpClient;
    }

    private void login() throws IOException {
        ZLog.i(TAG, ZI18n.getString("client_wrapper.info.try_connect"), hostname, port);
        ftpClient.connect(hostname, port);
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ZLog.e(TAG, ZI18n.getString("client_wrapper.error.unable_connect"), hostname, port);
            throw new IOException("Unable to connect to FTP server");
        }
        ftpClient.enterLocalPassiveMode();
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        ZLog.i(TAG, ZI18n.getString("client_wrapper.info.try_login"));
        ftpClient.login(username, password);
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ZLog.e(TAG, ZI18n.getString("client_wrapper.error.unable_login"));
            throw new IOException("Unable to login to FTP server");
        } else {
            ZLog.i(TAG, ZI18n.getString("client_wrapper.info.login_successful"));
        }
    }
}
